package com.ruoyi.web.core.config;


import com.alibaba.fastjson2.JSONObject;

import com.ruoyi.web.config.Gitconfig;
import com.ruoyi.web.util.WebUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class GiteeController {



    @RequestMapping("/giteeLogin")
    public Object giteeLogin(String code) {
        return "redirect:https://gitee.com/oauth/authorize?client_id=212052a223853ab59f460460a178b2d6fc76dafd81bab59dd1442d34e93ccd75&redirect_uri=http://localhost:8080/Giteelogin&response_type=code";
    }

    @RequestMapping("/Giteelogin")
        @ResponseBody
public Object callBack(String code) {
        //1、通过code获取access_token   授权token
        String urlStr = "https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}";
        urlStr = urlStr.replace("{code}", code)
                .replace("{client_id}", Gitconfig.client_id)
                .replace("{redirect_uri}", Gitconfig.redirect_uri)
                .replace("{client_secret}", Gitconfig.client_secret);
        try {
            String accessToken = WebUtil.post(urlStr, null, "UTF-8");
            System.out.println("accessToken:" + accessToken);
            JSONObject temp = JSONObject.parse(accessToken);
            //2、通过  access_token  获取用户信息


            String userInfo = "https://gitee.com/api/v5/user?";
            Map<String, String> params = new HashMap<>();
            params.put("access_token", temp.getString("access_token"));
           String userStr= WebUtil.get(userInfo, params, "UTF-8");

            JSONObject userMap = JSONObject.parse(userStr);
            String userId= userMap.getString("id");
            // 3、userId 去数据判断 该用户是否存在



        } catch (IOException e) {
            e.printStackTrace();
        }


        return code;
    }
}
